from OpenGL.GLUT import *
from OpenGL.GLU import *
from OpenGL.GL import *
from OpenGL.GL.ARB.shader_objects import *
from OpenGL.GL.ARB.fragment_shader import *
from OpenGL.GL.ARB.vertex_shader import *
from ShaderWrapper import *
 
import sys, time

# animation data
anglex, angley = 0, 0
animation = 0
t = 0


def idle():
    global anglex, angley, animation, t
    if animation:
        anglex = (anglex+1)%360
        angley = (angley+1)%360
        if anglex==0:
            animation, t = 0, 0
        sw.send_float("timeStep", t-int(t))
        t = time.clock()
        glutPostRedisplay()
    
    
def keyboard(key, x, y):
    global animation
    if key==chr(27): # chr(27) == EsCAPE
        sys.exit()
    if key=='a' or key=='a':
        animation = (animation+1)%2
    glutPostRedisplay()
    

def display():
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
    glMatrixMode(GL_MODELVIEW)
    glLoadIdentity()
    glRotate(anglex, 1,0,0)
    glRotate(angley, 0,1,0)

    gluSphere(gluNewQuadric(), 0.5, 10, 10)
    glutSwapBuffers()


def initGL(width, height):
    global sw

    # creating ShaderWrapper
    sw = ShaderWrapper("brick_shader", path="")
    #sw = ShaderWrapper("simpleColor_shader", path="")
    
    # creating a rendering context
    glutInit(sys.argv)
    glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH)
    glutInitWindowSize(width, height)
    glutCreateWindow("GLSL example")  
    
    # add callback functions
    glutDisplayFunc(display)
    glutIdleFunc(idle)
    glutKeyboardFunc(keyboard)
    
    # checking wether system supports ARB_(fragment,vertex)_programm extension
    if not glInitShaderObjectsARB():
    	raise RuntimeError( 
			"""ARB Shader Objects extension is required """
			"""but not supported on this machine!""" )

    #Shader anwerfen
    sw.init_vertex_shader()
    print "vertex_shader initialisiert!"
    sw.init_fragment_shader()
    print "fragment_shader initialisiert!"
    sw.link_shaders()
    print "Shader gelinkt!"
    sw.use_shader_program()

    #Attribute hinzufuegen
    sw.send_vec3("BrickColor", (1.0, 0.3, 0.2))
    sw.send_vec3("MortarColor", (0.85, 0.86, 0.84))
    sw.send_vec2("BrickSize", (0.30, 0.15))
    sw.send_vec2("BrickPct", (0.90, 0.85))
    sw.send_vec3("LightPosition", (0.0, 0.0, -4.0))
    
  
    glEnable(GL_DEPTH_TEST)
    glEnable(GL_LIGHTING)
    glEnable(GL_LIGHT0)
    glLightfv(GL_LIGHT0, GL_POSITION, [4.0, 3.0, -2.0 ,1.0])
    
   

if __name__ == "__main__":
    initGL(400, 400)
    glutMainLoop()
    
